package com.veo.dao;

import com.veo.domain.Role;
import com.veo.domain.UserInfo;
import org.apache.ibatis.annotations.*;


import java.util.List;

public interface UserDao {

    //根据姓名查用户的信息
    @Select("select * from users where username=#{username}")
    @Results({
            @Result(id = true,column = "id",property = "id"),
            @Result(column = "username",property = "username"),
            @Result(column = "email", property = "email"),
            @Result(column = "password", property = "password"),
            @Result(column = "phoneNum", property = "phoneNum"),
            @Result(column = "status", property = "status"),
            @Result(column = "id", property = "roles", javaType = List.class, many = @Many(select = "com.veo.dao.RolesDao.findRoleById"))
    })
    UserInfo findUserByName(String username);

    //查询所有用户
    //@Select("select * from users")
    @Select("<script>" + "select * from users "+"<where>"+
            "<if test=\"searcherName!= null and searcherName!=''\"> username like concat(#{searcherName},'%')</if>"+
            "</where>"+
            "</script>")
    List<UserInfo> findAllUser(@Param("searcherName") String searcherName);

    //添加用户
    @Insert("insert into users(id,email,username,password,phoneNum,status) values(#{id},#{email},#{username},#{password},#{phoneNum},#{status})")
    int addUser(UserInfo userInfo);

    //根据id查用户
    @Select("select * from users where id=#{id}")
    @Results({
            @Result(id = true,column = "id",property = "id"),
            @Result(column = "username",property = "username"),
            @Result(column = "email", property = "email"),
            @Result(column = "password", property = "password"),
            @Result(column = "phoneNum", property = "phoneNum"),
            @Result(column = "status", property = "status"),
            @Result(column = "id",property = "roles",javaType = List.class,many = @Many(select = "com.veo.dao.RolesDao.findRoleById"))
    })
    UserInfo findUserById(String id);


    //查找当前用户可用的角色
    @Select("select * from role where id not in (select roleId from users_role where userId=#{userId})")
    List<Role> findOtherRole(String userId);

    //为用户添加多个或一个角色
    @Insert("insert into users_role(userId,roleId) values(#{userId},#{roleId})")
    int addRoleToUser(@Param(value = "userId") String userId, @Param(value = "roleId") String roleId);

    @Select("select * from users where id in (select userId from users_role where roleId=#{roleId})")
    List<UserInfo> findUserByRoleId(String roleId);


    //根据id删除用户
    @Delete("delete from users_role where userId=#{id}")
    int deleteUserRoleId(String id);
    @Delete("delete from users where id=#{id}")
    int deleteUserById(String id);

}
